﻿using UnityEngine;
using UnityEngine.UI;
using System.Collections.Generic;
using UnityEditor;
using System;
public class GameObjectMenu 
{
    public static List<GameObject> CreateNewControlInHierarchy(string newName = "Default", params Type[] types)
    {
        List<GameObject> newList = new List<GameObject>();

        if (Selection.gameObjects.Length <= 0)   // no selection
        {
            GameObject canvasObject = GetDefaultCanvasObject();
            Selection.activeGameObject = CreateNewObject(canvasObject, newName, types);
            newList.Add(Selection.activeGameObject);
        }
        else
        {
            GameObject[] selectedObjects = Selection.gameObjects;
            //Debug.Log("Selected : " + selectedObjects.Length);
            for (int i = 0; i < selectedObjects.Length; i++)
                newList.Add(CreateNewObject(selectedObjects[i], newName, types));
            Selection.objects = newList.ToArray();
        }
        return newList;
    }

    public static GameObject CreateNewObject(GameObject parentObject, string newName = "Default", params Type[] types)
    {
        GameObject newObject = GetNewGameObjectWithComponent(newName, types);
        newObject.transform.SetParent(parentObject.transform);
        newObject.transform.localPosition = Vector3.zero;
        newObject.transform.localScale = Vector3.one;
        newObject.transform.SetAsLastSibling();
        return newObject;
    }

    private static GameObject GetNewGameObjectWithComponent(string name, params Type[] types)
    {
        GameObject newControlObject = new GameObject(name);
        newControlObject.AddComponent<RectTransform>();
        foreach (Type type in types)
            newControlObject.AddComponent(type);
        return newControlObject;
    }

    public static GameObject GetDefaultCanvasObject()
    {
        Canvas canvas = GameObject.FindObjectOfType<Canvas>();
        GameObject result = null;

        if (canvas)
            result = canvas.gameObject;
        else
        {
            result = new GameObject("Canvas");
            result.AddComponent<Canvas>();
            result.AddComponent<CanvasScaler>();
            result.AddComponent<GraphicRaycaster>();
        }
        return result;
    }

}
